//
//  SearchCityViewController.m
//  MIDI
//
//  Created by 千行时线 on 15/9/20.
//  Copyright (c) 2015年 QXSX. All rights reserved.
//

#import "SearchCityViewController.h"
#import "AppConfig.h"
#import "UserDataSingleton.h"

@interface SearchCityViewController ()<UITableViewDelegate , UITableViewDataSource,UISearchBarDelegate>
@property (weak, nonatomic) IBOutlet UITableView *myTableView;
@property (weak, nonatomic) IBOutlet UILabel *currCityLable;
@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
@property (weak, nonatomic) IBOutlet UIView *viewCurCity;
@property (weak, nonatomic) IBOutlet UIView *viewSelectedCity;
@property (weak, nonatomic) IBOutlet UIView *view1;
@property (weak, nonatomic) IBOutlet UIView *view3;


@property (nonatomic, strong) NSMutableDictionary *cities;

@property (nonatomic, strong) NSMutableArray *keys; //城市首字母
@property (nonatomic, strong) NSMutableArray *arrayCitys;   //城市数据
@property (nonatomic, strong) NSMutableArray *arrayHotCity;

@property(nonatomic, assign) BOOL isSearch;//是否是search状态
@property (strong, nonatomic)NSMutableArray *showData;

@end

@implementation SearchCityViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    [self getCityData];
    self.myTableView.dataSource = self;
    self.myTableView.delegate  = self;
    self.myTableView.autoresizingMask = (UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight);
    self.myTableView.backgroundColor = [UIColor clearColor];
    self.myTableView.sectionIndexColor = UIColorRGBA(19, 208, 202, 1);
    
    self.searchBar.delegate = self;
    self.isSearch = NO;
    
    //手势
    UITapGestureRecognizer *tapGestureRecognizer1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap)];
    [self.viewCurCity addGestureRecognizer:tapGestureRecognizer1];
    
    UITapGestureRecognizer *tapGestureRecognizer2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap)];
    [self.viewSelectedCity addGestureRecognizer:tapGestureRecognizer2];
    
    UITapGestureRecognizer *tapGestureRecognizer3 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap)];
    [self.view1 addGestureRecognizer:tapGestureRecognizer3];
    
    UITapGestureRecognizer *tapGestureRecognizer4 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap)];
    [self.view3 addGestureRecognizer:tapGestureRecognizer4];
    
    //当前城市
    self.currCityLable.text = [UserDataSingleton shareInstance].cityName;
    
    //已选城市
    if ([UserDataSingleton shareInstance].selectedCity == nil
        || [[UserDataSingleton shareInstance].selectedCity isEqualToString:@""])
    {
        self.selectCityLable.text = [UserDataSingleton shareInstance].cityName;
        
        [UserDataSingleton shareInstance].selectedCity
                            = [UserDataSingleton shareInstance].cityName;
    }
    else
    {
        self.selectCityLable.text = [UserDataSingleton shareInstance].selectedCity;
    }
}

-(void)tap
{
    [self.searchBar resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self configNavigationItem];
}

-(void) configNavigationItem
{
    [self.navigationController.navigationBar setBarTintColor:MIDIColorOfNavigationBar];
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    self.navigationItem.title = @"选择城市";
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],UITextAttributeTextColor, [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0],UITextAttributeTextShadowColor,[UIFont fontWithName:@"Hiragino Sans GB" size:18.0],UITextAttributeFont,nil]];
    
    [self configNavigationBackAction:^{
        
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
}

-(void)pressLeft:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 获取城市数据
-(void)getCityData
{
    self.arrayHotCity = [NSMutableArray arrayWithObjects:@"广州市",@"北京市",@"天津市",@"西安市",@"重庆市",@"沈阳市",@"青岛市",@"济南市",@"深圳市",@"长沙市",@"无锡市", nil];
    self.keys = [NSMutableArray array];
    self.arrayCitys = [NSMutableArray array];
    NSString *path=[[NSBundle mainBundle] pathForResource:@"citydict"
                                                   ofType:@"plist"];
    self.cities = [NSMutableDictionary dictionaryWithContentsOfFile:path];
    
    [self.keys addObjectsFromArray:[[self.cities allKeys] sortedArrayUsingSelector:@selector(compare:)]];
    
    //添加热门城市
    NSString *strHot = @"热";
    [self.keys insertObject:strHot atIndex:0];
    [self.cities setObject:_arrayHotCity forKey:strHot];
    
    self.showData = [[NSMutableArray alloc] init];
}

#pragma mark - tableView
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 24.0;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, 24)];
    bgView.backgroundColor = UIColorRGBA(242, 243, 246, 1);
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(16, 2, 250, 20)];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.font = [UIFont fontWithName:@"Hiragino Sans GB" size:12.0];
    
    NSString *key = [_keys objectAtIndex:section];
    if ([key rangeOfString:@"热"].location != NSNotFound) {
        titleLabel.text = @"热门城市";
    }
    else
        titleLabel.text = key;
    
    [bgView addSubview:titleLabel];
    
    return bgView;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if (self.isSearch)
        return nil;
    
    return _keys;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //搜索出来只显示一块
    if (self.isSearch) {
        return 1;
    }
    
    return [_keys count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.isSearch) {
        return [self.showData count];
    }
    
    NSString *key = [_keys objectAtIndex:section];
    NSArray *citySection = [_cities objectForKey:key];
    return [citySection count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"SearchCityCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
        cell.backgroundColor = [UIColor clearColor];
        cell.contentView.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        [cell.textLabel setTextColor:[UIColor blackColor]];
        cell.textLabel.font = [UIFont fontWithName:@"Hiragino Sans GB" size:15.0];
    }

    if (self.isSearch)
    {
        NSString *cityName = [self.showData objectAtIndex:indexPath.row];
        cell.textLabel.text = cityName;
    }
    else
    {
        NSString *key = [_keys objectAtIndex:indexPath.section];
        cell.textLabel.text = [[_cities objectForKey:key] objectAtIndex:indexPath.row];
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    self.selectCityLable.text = cell.textLabel.text;
    
    [UserDataSingleton shareInstance].selectedCity = cell.textLabel.text;
    
    if ([self.delegate respondsToSelector:@selector(setExamCity:)])
        [self.delegate setExamCity:cell.textLabel.text];
    
    [self.searchBar resignFirstResponder];
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [self.showData removeAllObjects];
    
    //去掉空格
    NSString *text = [searchText stringByTrimmingCharactersInSet:
                               [NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    if (text.length == 0)
    {
        self.isSearch = NO;
    }
    else
    {
        self.isSearch = YES;
        
        NSArray *cityAry = [self.cities allValues];
        
        for (NSArray *keyAry in cityAry)
        {
            for (NSString *city in keyAry)
            {
                NSRange chinese = [city rangeOfString:text options:NSCaseInsensitiveSearch];
                
                if (chinese.location != NSNotFound)
                {
                    if (![self.showData containsObject:city])
                        [self.showData addObject:city];
                }
            }
        }
        
        for (NSString *k in self.keys)
        {
            NSRange letters = [k rangeOfString:text options:NSCaseInsensitiveSearch];
        
            if (letters.location != NSNotFound)
            {
                cityAry = [self.cities objectForKey:k];
                
                for (NSString *object in cityAry)
                {
                    [self.showData addObject:object];
                }
                break;
            }
        }
    }
    [self.myTableView reloadData];
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
}


@end





















